import 'dart:collection';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:go_router/go_router.dart';
import 'package:zywz/widgets/EmptyPlaceholder.dart';
import '../../bloc/service/service_bloc.dart';
import '../../generated/assets.dart';
import '../../models/services_data.dart';
import '../../widgets/financial_card.dart';
import '../../config/app_colors.dart';

class ServicesPageDetail extends StatefulWidget {
  const ServicesPageDetail({super.key});

  @override
  State<ServicesPageDetail> createState() => _ServicesPageDetailState();
}

class _ServicesPageDetailState extends State<ServicesPageDetail>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  ServicesBean? extraData;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // context.read<ServiceBloc>().add(ServiceEventInit());
    });
  }

  @override
  Widget build(BuildContext context) {
    // 获取路由状态
    final state = GoRouterState.of(context);
    // 获取 extra 数据
    extraData = state.extra as ServicesBean?;
    print('object ${extraData?.toJson()}');

    return Scaffold(
      appBar: AppBar(
        backgroundColor: const Color(0xFF41C7DD),
        elevation: 0,
        centerTitle: true,
        title: Text(
          extraData?.serviceName ?? '税局信息验证',
          style: const TextStyle(
            color: Colors.white,
            fontSize: 18.0,
            fontWeight: FontWeight.bold,
          ),
        ),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () {
            context.pop();
          },
        ),
      ),
      body: Column(
        children: [
          Expanded(
            child: Container(
              decoration: const BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [Color(0xFFE0F7FA), Color(0xFFE0F7FA)],
                ),
              ),
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    Image.network(
                      'https://hongfund-app.oss-cn-hangzhou.aliyuncs.com/image/01.jpg',
                    ),
                    // CachedNetworkImage(
                    //   imageUrl:
                    //       'https://hongfund-app.oss-cn-hangzhou.aliyuncs.com/image/01.jpg',
                    //   placeholder: (context, url) =>
                    //       const CircularProgressIndicator(),
                    //   errorWidget: (context, url, error) => const Icon(Icons.error),
                    //   fit: BoxFit.cover,
                    // ),

                    Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(15),
                        child: Column(
                          children: [
                            Container(
                              constraints: BoxConstraints(minHeight: 40),
                              color: Color(0xFF41C7DD),
                              child: Row(
                                children: [
                                  Flexible(
                                    flex: 2,
                                    fit: FlexFit.tight,
                                    child: Center(child: Text('产品名称')),
                                  ),
                                  Flexible(
                                    flex: 1,
                                    fit: FlexFit.tight,
                                    child: Center(child: Text('价格')),
                                  ),
                                  Flexible(
                                    flex: 1,
                                    fit: FlexFit.tight,
                                    child: Center(child: Text('操作')),
                                  ),
                                ],
                              ),
                            ),
                            Container(
                              constraints: BoxConstraints(minHeight: 40),
                              padding: const EdgeInsets.only(bottom: 16),
                              color: Colors.white,
                              child: Row(
                                children: [
                                  Flexible(
                                    flex: 2,
                                    fit: FlexFit.tight,
                                    child: Center(child:Padding(
                                      padding: const EdgeInsets.only(left: 8.0,right: 8,top: 8),
                                      child: Column(
                                        children: [
                                          Text(extraData?.serviceName ?? '税局信息验证'),
                                          Center(child: Text(extraData?.detail ?? '税局信息验证',
                                            textAlign: TextAlign.center,
                                            style: TextStyle(fontSize: 11,color: Colors.grey),)),
                                        ],
                                      ),
                                    )),
                                  ),
                                  Flexible(
                                    flex: 1,
                                    fit: FlexFit.tight,
                                    child: Center(child: Row(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                        Text('${extraData?.price}',style: TextStyle(fontSize: 17,fontWeight: FontWeight.bold),),
                                        Text('${extraData?.unit}'),
                                      ],
                                    )),
                                  ),
                                  Flexible(
                                    flex: 1,
                                    fit: FlexFit.tight,
                                    child: Center(child:   BlocListener<ServiceBloc,ServiceState>(
                                      listener: (context, state) {
                                        if(state is ServiceLoadingState){
                                          EasyLoading.show(status: '购买中');
                                          return;
                                        }else if(state is ServiceErrorState){
                                          EasyLoading.dismiss(animation: false);
                                          EasyLoading.showToast(state.message);
                                        }else if(state is ServiceBuySuccessState){
                                          EasyLoading.dismiss(animation: false);
                                          EasyLoading.showToast("WXPAY");
                                        }

                                      },
                                      child: SizedBox(
                                        height: 26,
                                        child: ElevatedButton(
                                          onPressed: () {

                                            final mapParam = LinkedHashMap<String, dynamic>();
                                            mapParam['serviceId'] = extraData?.serviceId;
                                            mapParam['serviceName'] = extraData?.serviceName;
                                            mapParam['amount'] = extraData?.price;
                                            mapParam['tradeType'] = 'APP';

                                            var bloc = context.read<ServiceBloc>();
                                            bloc.add(ServiceOrderBuyEven(mapParam));
                                          },
                                          style: ElevatedButton.styleFrom(
                                            backgroundColor: const Color(0xFF4DD0E1),
                                            foregroundColor: Colors.white,
                                            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
                                            padding: const EdgeInsets.symmetric(horizontal: 11),
                                          ),
                                          child: Text('立即购买'),
                                        ),
                                      ),
                                    ),),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),

                    Image.network(
                      'https://hongfund-app.oss-cn-hangzhou.aliyuncs.com/image/02.jpg',
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildHeaderCard() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(15),
        gradient: const LinearGradient(
          colors: [Color(0xFF29B6F6), Color(0xFF4DD0E1)],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
      ),
      child: const Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '结合大数据+AI智能分析',
            style: TextStyle(
              color: Colors.white,
              fontSize: 22,
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(height: 8),
          Text(
            '企业税务合规专家服务体系',
            style: TextStyle(color: Colors.white70, fontSize: 16),
          ),
        ],
      ),
    );
  }

  Widget _buildServiceSection(String title, List<Widget> items) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Container(
              width: 3,
              height: 15,
              color: AppColors.primaryColor,
              margin: const EdgeInsets.only(right: 8),
            ),
            Text(
              title,
              style: const TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
            ),
            // TextButton(
            //   onPressed: () => GoRouter.of(context).push('/service-detail'),
            //   child: const Text('查看订单', style: TextStyle(color: Color(0xFF41C7DD))),
            // ),
          ],
        ),
        const SizedBox(height: 8),
        Divider(),
        const SizedBox(height: 8),
        ...items,
      ],
    );
  }

  Widget _buildServiceItem(
    String title,
    String price,
    String description,
    String buttonText,
    String unit,
  ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              child: Text(
                title,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(right: 16.0),
              child: Text.rich(
                TextSpan(
                  children: [
                    TextSpan(
                      text: price,
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        color: Colors.black,
                        fontSize: 17,
                      ),
                    ),
                    TextSpan(
                      text: unit,
                      style: TextStyle(color: Colors.black),
                    ),
                  ],
                ),
              ),
            ),
            SizedBox(
              height: 26,
              child: ElevatedButton(
                onPressed: () {},
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF4DD0E1),
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                  ),
                  padding: const EdgeInsets.symmetric(horizontal: 11),
                ),
                child: Text('立即购买'),
              ),
            ),
          ],
        ),
        const SizedBox(height: 8),
        Container(
          padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: const Color(0xFFE0F7FA),
            borderRadius: BorderRadius.circular(6),
          ),
          child: Column(
            children: [
              Text(
                description,
                style: const TextStyle(color: Colors.black, height: 1.5),
              ),
              if (buttonText.isNotEmpty)
                Align(
                  alignment: Alignment.centerRight,
                  child: Text(
                    '查看详情',
                    style: const TextStyle(color: Colors.blue),
                  ),
                ),
            ],
          ),
        ),
        const SizedBox(height: 16),
      ],
    );
  }
}
